#!/Pub/Apps/bin/Rscript
suppressPackageStartupMessages(library(argparse))

wrp <- "转化生成loom文件，需要两个参数，第一个为seurat对象路径(rds or rdata)，第二个为od输出路径。可选conuts或者data。"
parser <- ArgumentParser(
    prog='seurat2loom_exprMat.r',
    description = wrp,
    formatter_class = "argparse.RawTextHelpFormatter"
    # usage = "seurat2loom_exprMat.r -h; seurat2loom_exprMat.r seurat_obj od"
)

parser$add_argument("seurat_obj", nargs = 1, help = "seurat对象路径。[rds or rdata]")
parser$add_argument("od", nargs = 1, help = "结果输出路径")
parser$add_argument("-t", "--type_of_data",
    action = "store",
    default = "data", metavar = "",
    help = "分析所用数据类型，貌似counts或者data都可以。默认data"
)

args_in_process <- parser$parse_args()

main <- \(){
    dir.create(args_in_process$od, recursive = T, showWarnings = F)

    suppressMessages(library(Seurat))
    suppressMessages(library(tidyverse))

    cli::cli_inform(">> 1.1 Load Seurat obj [{Sys.time()}]\n")

    fn <- basename(args_in_process$seurat_obj)
    if (grepl("rds", fn, ignore.case = T)) {
        ss_tmp <- readRDS(args_in_process$seurat_obj)
    }
    if (grepl("rdata", fn, ignore.case = T)) {
        tmp <- load(args_in_process$seurat_obj)
        ss_tmp <- get0(tmp)
    }

    f <- function() {
        cli::cli_alert_info("Seurat info:\n")
        print(ss_tmp)
        cat("\n")
    }

    exprMat <- switch(args_in_process$type_of_data,
        data = {
            if (startsWith(as.character(utils::packageVersion("Seurat")), "5")) {
                exprMat <- ss_tmp@assays$RNA$data
            } else {
                exprMat <- ss_tmp@assays$RNA@data
            }
        },
        counts = {
            if (startsWith(as.character(utils::packageVersion("Seurat")), "5")) {
                exprMat <- ss_tmp@assays$RNA$counts
            } else {
                exprMat <- ss_tmp@assays$RNA@counts
            }
        }
    )

    cli::cli_inform(">> 1.2 Save exprMat and cell annotation to feather [{Sys.time()}]\n")
    exprMat <- exprMat %>% as.data.frame() %>% rownames_to_column('gene')    
    arrow::write_feather(exprMat,str_glue("{args_in_process$od}/seurat_obj_expression.feather"))

    cellInfo <- ss_tmp@meta.data %>% as.data.frame() %>% rownames_to_column('cell')
    write_tsv(cellInfo,str_glue("{args_in_process$od}/seurat_obj_cellInfo.tsv"))

    cli::cli_inform(">> 1.4 Converting Over [{Sys.time()}]\n")
}

if (file.exists(stringr::str_glue("{args_in_process$od}/seurat_obj_expression.feather"))) {
    cli::cli_alert_warning("\nseurat_obj_expression.feather已生成，exprMat转化跳过\n")
} else {
    main()
}

